<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col :span="24">
        <el-card>
          <div slot="header" class="clearfix">
            <span>健康数据监控</span>
            <el-button style="float: right; padding: 3px 0" type="text" @click="refreshData">刷新数据</el-button>
          </div>
          
          <!-- 设备选择 -->
          <el-form :inline="true" class="demo-form-inline">
            <el-form-item label="设备ID">
              <el-input v-model="iotId" placeholder="请输入设备ID" style="width: 200px"></el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="loadHealthData">查询</el-button>
            </el-form-item>
          </el-form>

          <!-- 健康数据展示 -->
          <el-row :gutter="20" v-if="healthData.length > 0">
            <!-- 心率卡片 -->
            <el-col :span="8">
              <el-card class="health-card" shadow="hover">
                <div class="health-card-header">
                  <i class="el-icon-heart"></i>
                  <span>心率</span>
                </div>
                <div class="health-card-content">
                  <div class="health-value">{{ getHeartRate() }}</div>
                  <div class="health-unit">次/分钟</div>
                </div>
                <div class="health-card-footer">
                  <span class="health-time">{{ getHeartRateTime() }}</span>
                </div>
              </el-card>
            </el-col>

            <!-- 呼吸率卡片 -->
            <el-col :span="8">
              <el-card class="health-card" shadow="hover">
                <div class="health-card-header">
                  <i class="el-icon-wind-power"></i>
                  <span>呼吸率</span>
                </div>
                <div class="health-card-content">
                  <div class="health-value">{{ getRespiratoryRate() }}</div>
                  <div class="health-unit">次/分钟</div>
                </div>
                <div class="health-card-footer">
                  <span class="health-time">{{ getRespiratoryRateTime() }}</span>
                </div>
              </el-card>
            </el-col>

            <!-- 睡眠状态卡片 -->
            <el-col :span="8">
              <el-card class="health-card" shadow="hover">
                <div class="health-card-header">
                  <i class="el-icon-moon"></i>
                  <span>睡眠状态</span>
                </div>
                <div class="health-card-content">
                  <div class="health-value">{{ getSleepPhaseState() }}</div>
                  <div class="health-unit">状态</div>
                </div>
                <div class="health-card-footer">
                  <span class="health-time">{{ getSleepPhaseStateTime() }}</span>
                </div>
              </el-card>
            </el-col>
          </el-row>

          <!-- 心率图表 -->
          <el-row :gutter="20" style="margin-top: 20px" v-if="heartRateData.length > 0">
            <el-col :span="24">
              <el-card>
                <div slot="header" class="clearfix">
                  <span>心率趋势图</span>
                </div>
                <div ref="heartRateChart" style="height: 400px;"></div>
              </el-card>
            </el-col>
          </el-row>

          <!-- 数据表格 -->
          <el-row :gutter="20" style="margin-top: 20px" v-if="healthData.length > 0">
            <el-col :span="24">
              <el-card>
                <div slot="header" class="clearfix">
                  <span>详细数据</span>
                </div>
                <el-table :data="healthData" style="width: 100%">
                  <el-table-column prop="functionId" label="功能ID" width="180"></el-table-column>
                  <el-table-column prop="value" label="数值" width="120"></el-table-column>
                  <el-table-column prop="eventTime" label="时间" width="200"></el-table-column>
                  <el-table-column label="状态" width="100">
                    <template slot-scope="scope">
                      <el-tag :type="getStatusType(scope.row.functionId)">
                        {{ getStatusText(scope.row.functionId) }}
                      </el-tag>
                    </template>
                  </el-table-column>
                </el-table>
              </el-card>
            </el-col>
          </el-row>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { queryServiceProperties } from '@/api/nursing/healthData'
import * as echarts from 'echarts'

export default {
  name: 'HealthData',
  data() {
    return {
      iotId: 'test_device_001', // 默认设备ID
      healthData: [],
      heartRateData: [],
      heartRateChart: null,
      timer: null
    }
  },
  mounted() {
    this.loadHealthData()
    // 启动定时刷新
    this.startAutoRefresh()
  },
  beforeDestroy() {
    if (this.timer) {
      clearInterval(this.timer)
    }
    if (this.heartRateChart) {
      this.heartRateChart.dispose()
    }
  },
  methods: {
    // 加载健康数据
    async loadHealthData() {
      try {
        const response = await queryServiceProperties(this.iotId)
        if (response.code === 200) {
          this.healthData = response.data
          this.updateHeartRateChart()
          this.$message.success('数据加载成功')
        } else {
          this.$message.error(response.msg || '数据加载失败')
        }
      } catch (error) {
        console.error('加载健康数据失败:', error)
        this.$message.error('数据加载失败')
      }
    },

    // 刷新数据
    refreshData() {
      this.loadHealthData()
    },

    // 启动自动刷新
    startAutoRefresh() {
      this.timer = setInterval(() => {
        this.loadHealthData()
      }, 30000) // 每30秒刷新一次
    },

    // 获取心率数据
    getHeartRate() {
      const heartRate = this.healthData.find(item => item.functionId === 'HeartRate')
      return heartRate ? heartRate.value : '--'
    },

    // 获取心率时间
    getHeartRateTime() {
      const heartRate = this.healthData.find(item => item.functionId === 'HeartRate')
      return heartRate ? this.formatTime(heartRate.eventTime) : '--'
    },

    // 获取呼吸率数据
    getRespiratoryRate() {
      const respiratoryRate = this.healthData.find(item => item.functionId === 'RespiratoryRate')
      return respiratoryRate ? respiratoryRate.value : '--'
    },

    // 获取呼吸率时间
    getRespiratoryRateTime() {
      const respiratoryRate = this.healthData.find(item => item.functionId === 'RespiratoryRate')
      return respiratoryRate ? this.formatTime(respiratoryRate.eventTime) : '--'
    },

    // 获取睡眠状态数据
    getSleepPhaseState() {
      const sleepState = this.healthData.find(item => item.functionId === 'SleepPhaseState')
      if (!sleepState) return '--'
      
      const stateMap = {
        0: '清醒',
        1: '浅睡',
        2: '深睡',
        3: 'REM'
      }
      return stateMap[sleepState.value] || sleepState.value
    },

    // 获取睡眠状态时间
    getSleepPhaseStateTime() {
      const sleepState = this.healthData.find(item => item.functionId === 'SleepPhaseState')
      return sleepState ? this.formatTime(sleepState.eventTime) : '--'
    },

    // 格式化时间
    formatTime(timeStr) {
      if (!timeStr) return '--'
      const date = new Date(timeStr)
      return date.toLocaleString('zh-CN')
    },

    // 获取状态类型
    getStatusType(functionId) {
      const statusMap = {
        'HeartRate': 'success',
        'RespiratoryRate': 'warning',
        'SleepPhaseState': 'info',
        'BedTime': 'primary',
        'BedExitCount': 'danger'
      }
      return statusMap[functionId] || 'info'
    },

    // 获取状态文本
    getStatusText(functionId) {
      const textMap = {
        'HeartRate': '正常',
        'RespiratoryRate': '正常',
        'SleepPhaseState': '正常',
        'BedTime': '正常',
        'BedExitCount': '正常'
      }
      return textMap[functionId] || '未知'
    },

    // 更新心率图表
    updateHeartRateChart() {
      // 模拟心率历史数据
      const now = new Date()
      const heartRateHistory = []
      for (let i = 0; i < 20; i++) {
        const time = new Date(now.getTime() - (19 - i) * 60000) // 每分钟一个数据点
        heartRateHistory.push({
          time: time.toLocaleTimeString('zh-CN', { hour12: false }),
          value: Math.floor(Math.random() * 20) + 60 // 60-80之间的随机心率
        })
      }
      
      // 添加当前心率
      const currentHeartRate = this.getHeartRate()
      if (currentHeartRate !== '--') {
        heartRateHistory.push({
          time: new Date().toLocaleTimeString('zh-CN', { hour12: false }),
          value: parseInt(currentHeartRate)
        })
      }

      this.heartRateData = heartRateHistory

      // 初始化图表
      this.$nextTick(() => {
        if (this.heartRateChart) {
          this.heartRateChart.dispose()
        }
        
        this.heartRateChart = echarts.init(this.$refs.heartRateChart)
        
        const option = {
          title: {
            text: '心率实时监控',
            left: 'center'
          },
          tooltip: {
            trigger: 'axis',
            formatter: function(params) {
              return params[0].name + '<br/>心率: ' + params[0].value + ' 次/分钟'
            }
          },
          xAxis: {
            type: 'category',
            data: heartRateHistory.map(item => item.time),
            axisLabel: {
              rotate: 45
            }
          },
          yAxis: {
            type: 'value',
            name: '心率 (次/分钟)',
            min: 50,
            max: 100
          },
          series: [{
            name: '心率',
            type: 'line',
            data: heartRateHistory.map(item => item.value),
            smooth: true,
            lineStyle: {
              color: '#ff4757'
            },
            areaStyle: {
              color: {
                type: 'linear',
                x: 0,
                y: 0,
                x2: 0,
                y2: 1,
                colorStops: [{
                  offset: 0, color: 'rgba(255, 71, 87, 0.3)'
                }, {
                  offset: 1, color: 'rgba(255, 71, 87, 0.1)'
                }]
              }
            },
            markPoint: {
              data: [
                { type: 'max', name: '最高值' },
                { type: 'min', name: '最低值' }
              ]
            }
          }]
        }
        
        this.heartRateChart.setOption(option)
      })
    }
  }
}
</script>

<style scoped>
.health-card {
  text-align: center;
  margin-bottom: 20px;
}

.health-card-header {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 15px;
  color: #606266;
}

.health-card-header i {
  font-size: 20px;
  margin-right: 8px;
}

.health-card-content {
  margin-bottom: 15px;
}

.health-value {
  font-size: 36px;
  font-weight: bold;
  color: #409EFF;
  margin-bottom: 5px;
}

.health-unit {
  font-size: 14px;
  color: #909399;
}

.health-card-footer {
  border-top: 1px solid #EBEEF5;
  padding-top: 10px;
}

.health-time {
  font-size: 12px;
  color: #C0C4CC;
}

.el-card {
  margin-bottom: 20px;
}
</style> 